var id;
var approvalType; // 审批类型

var approvalType = ly.getUrlParam("approvalType");
var updateUrl = ''; // 新增/编辑接口
if (approvalType == 1) { // 补卡
  updateUrl = site.apiUrl + '/back/approvalSettings/insertOrUpdateCardReissuePacketRecord';
} else if (approvalType == 2) { // 请假
  updateUrl = site.apiUrl + '/back/approvalSettings/insertOrUpdateAskForLeavePacketRecord';
} else if (approvalType == 3) { // 外出
  updateUrl = site.apiUrl + '/back/approvalSettings/insertOrUpdateGoOutPacketRecord';
}

// 选择ztree
var setting = {
  check: {
    enable: true
  },
  data: {
    simpleData: {
      enable: false
    }
  },
  view: {
    showIcon: false
	},
	callback: {
		onCheck: zTreeOnCheck,
	}
};

// zTree发生改变
function zTreeOnCheck(event, treeId, treeNode) {
  var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
  var checkedNodes = zTreeObj.getCheckedNodes();
  $("#ztreeCheckedNames").html('');
  for(var i = 0; i < checkedNodes.length; i++) {
    if (!checkedNodes[i].children) {
      $("#ztreeCheckedNames").append('<li>'+ checkedNodes[i].name +'</li>')
    }
  }
};
// 获取zTree选中的值
function getzTreeChecked() {
  participantId = [];
  var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
  var checkedNodes = zTreeObj.getCheckedNodes();
  var currStr='';
  $.each(checkedNodes, function(i, o) {
    if (checkedNodes[i].userId) {
      participantId.push(checkedNodes[i].userId);
      if(i==checkedNodes.length-1){
        currStr +=checkedNodes[i].name+"&nbsp;&nbsp;&nbsp;&nbsp;";
      }else{
        currStr +=checkedNodes[i].name+'、';
      }
    }
  })
  $(".applicant").html(currStr);
}
// 选择ztree radio
var radioSetting = {
  check: {
    enable: true,
    chkStyle: "radio",
		radioType: "all"
  },
  data: {
    simpleData: {
      enable: false
    }
  },
  view: {
    showIcon: false
	},
	callback: {
    beforeCheck: zTreeBeforeCheck,
		onCheck: zTreeRadioOnCheck,
	}
};

function zTreeBeforeCheck(treeId, treeNode) {
    return !treeNode.isParent;//当是父节点 返回false 不让选取
}
// zTree-Radio发生改变
function zTreeRadioOnCheck(event, treeId, treeNode) {
  var zTreeObj = $.fn.zTree.getZTreeObj("treeRadioDemo"); // ztree的Id
  var checkedNodes = zTreeObj.getCheckedNodes();
  $("#ztreeRadioCheckedNames").html('');
  for(var i = 0; i < checkedNodes.length; i++) {
      $("#ztreeRadioCheckedNames").append('<li>'+ checkedNodes[i].name +'</li>')
  }
};
// 获取zTree-Radio选中的值
function getzTreeRadioChecked() {
  approvedBy = [];
  var zTreeObj = $.fn.zTree.getZTreeObj("treeRadioDemo"); // ztree的Id
  var checkedNodes = zTreeObj.getCheckedNodes();
  var currStr='';
  $.each(checkedNodes, function(i, o) {
    if (checkedNodes[i].userId) {
      approvedBy.push(checkedNodes[i].userId);
      if(i==checkedNodes.length-1){
        currStr +=checkedNodes[i].name+"&nbsp;&nbsp;&nbsp;&nbsp;";
      }else{
        currStr +=checkedNodes[i].name+'、';
      }
    }
  })
  $(".approver").html(currStr);
}
/**标准数据格式*/
var zNodes = [];

// 选中的zTree值
var participantId = [];

// 选中的zTree-radio值
var approvedBy = [];

$(function() {
  $(".validform").createForm();
  id = ly.getUrlParam("id") || '';
  if (id) {
    $(".body_title").html("编辑");
    $(".form").getForm({
      id: id,
      approvalType: approvalType,
      ajaxform: true,
    }, function(data) {
			getTeamUser(data); // 获取部门与人员集合
      if(data.applicantList&&data.applicantList.length){
        var currStr='';
        for (var i = 0; i <data.applicantList.length; i++) {
          var usersInfo = data.applicantList[i];
            if(i==data.applicantList.length-1){
              currStr +=usersInfo.nickName+"&nbsp;&nbsp;&nbsp;&nbsp;";
            }else{
              currStr +=usersInfo.nickName+'、'
            }
        }
        $(".applicant").html(currStr);
      }
      $(".approver").html(data&&data.approver&&data.approver.nickName?data.approver.nickName+"&nbsp;&nbsp;&nbsp;&nbsp;":'');
			$("#attendanceStartTime").val(data.attendanceStartTime + ':00'); // 考勤开始时间
			$("#attendanceEndTime").val(data.attendanceEndTime + ':00'); // 考勤结束时间
    });
  } else {
		getTeamUser(); // 获取部门与人员集合

  }
  //获取到选择的值
  $("body").on("click", "input[name='userType']", function() {
    var userType = this.value;
    if (userType == '2') {
      $("#changeBusinessId").removeClass("hide");
      selectbusinessList(businessId);
    } else {
      $("#changeBusinessId").addClass("hide");
    }
  });

  //提交
  $("body").on("click", "#save", function(event) {
    event.preventDefault();
    var success = $('.form').validate('submitValidate');
    var packetName = $("#packetName").val(); // 分组名称
		
		// 获取申请人id字符串集
    var participantIdArr = participantId.toString() + ',';
    
    // 获取审批人id字符串集
    var approvedByArr = approvedBy.toString() + ',';

		if (participantId == '') {
			ly.toast('请选择申请人');
      return;
    }

    if (approvedBy == '') {
			ly.toast('请选择审批人');
      return;
    }

    if (success) {
      var obj = {};
      var url = updateUrl;
      if (id) {
        //修改
        obj = {
					'packetId': id,
          'packetName': packetName,
          'applicantIdS': participantIdArr,
          'approvedBy': approvedByArr,
        };
      } else {
        //新增
        obj = {
          'packetName': packetName,
          'applicantIdS': participantIdArr,
          'approvedBy': approvedByArr,
        };
      }

      request({
        url: url,
        data: obj,
        type: "post",
        callback: function(f) {
          if (f.code == "rest.success") {
            if (id == '') {
              ly.alert('保存成功', function() {
                ly.goto("approval-group-list.html?approvalType=" + approvalType);
              });
            } else {
              ly.alert('修改成功', function() {
                ly.goto("approval-group-list.html?approvalType=" + approvalType);
              });
            }
          } else {
            ly.toast(f.desc);
          }
        }
      });

    }
  })

	// 点击显示--选择部门人员弹窗
  $("#changePerson").on("click", function() {
    layer.open({
      title: false,
      type: 1,
      area: ['600px'], //设置宽度,高度自适应
      closeBtn: 0,
      content: $(".choose_person_container"),
      success: function(layero, index) {
        $("#layui-layer" + index).find(".goback,.icon-close").on("click", function() {
					layer.close(index);
        });
        $("#sayerBox-btn").on("click", function() {
					getzTreeChecked();
					ly.toast('选择成功','',500)
					layer.close(index);
        })
      }
    });
  })

  // 打开选择审批人弹窗
  $("#changeSPperson").on("click", function() {
    layer.open({
      title: false,
      type: 1,
      area: ['600px'], //设置宽度,高度自适应
      closeBtn: 0,
      content: $(".choose_sp_person_container"),
      success: function(layero, index) {
        $("#layui-layer" + index).find(".goback, .icon-close").on("click", function() {
					layer.close(index);
        });
        $("#save_sp_choose").on("click", function() {
					getzTreeRadioChecked();
					ly.toast('选择成功')
					layer.close(index);
        })
      }
    });
  })

});


// 获取部门与人员集合
function getTeamUser(viewData) {
	request({
    url: site.apiUrl + "/back/team/selectTeamUserByGroupsBack",
    type: "get",
    callback: function(f) {
      if (f.code == "rest.success") {
				zNodes = f.result;
        if (!viewData) { // 新增
          // ztree-checkbox
					$("#ztreeCheckedNames").html('');
					$.fn.zTree.init($("#treeDemo"), setting, zNodes); // 加载ztree
					var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
					zTreeObj.checkAllNodes(false); // 清除所有节点选中状态
          zTreeObj.expandAll(false); // 收起所有节点
          
          // ztree-radio
          $("#ztreeRadioCheckedNames").html('');

          // ztree-radio
          var viewCheckedRadioPerson = zNodes.map(function (item) {
            // console.log(item)
              item.chkDisabled= true;
              item.nocheck =true;
              return item;
          })
          $.fn.zTree.init($("#treeRadioDemo"), radioSetting, viewCheckedRadioPerson); // 加载ztree-radio
          var zTreeRadioObj = $.fn.zTree.getZTreeObj("treeRadioDemo"); // ztree的Id
					zTreeRadioObj.checkAllNodes(false); // 清除所有节点选中状态
          zTreeRadioObj.expandAll(false); // 收起所有节点
        } else { // 编辑
          // ztree-checkbox
					var viewCheckedPerson = zNodes.map(function (item) {
						if (item.children && item.children.length > 0) {
							var childrenCheckOption = item.children;
							var newChildren = childrenCheckOption.map(function (itm) {
								// 判断选中项，true设置cheked=true，反之设为false
								var isCheckedOption = viewData.applicantList.some(function (items) {
									return items.userId === itm.userId;
								});
								if (isCheckedOption) {
									itm.checked = true; // 为true时zTree勾选当前项
								} else {
									itm.checked = false;
								}
								return itm;
							});
							item.children = newChildren;
							return item;
						} else {
              return item;
            }
          });
					$.fn.zTree.init($("#treeDemo"), setting, viewCheckedPerson); // 加载ztree
					var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo"); // ztree的Id
					zTreeObj.expandAll(false); // 收起所有节点
          zTreeOnCheck(); // 展示右侧选中项

          // 设置编辑默认选中值
          participantId = [];
          $.each(viewData.applicantList, function(i, o) {
            participantId.push(viewData.applicantList[i].userId);
          })
          // ztree-radio
          var viewCheckedRadioPerson = zNodes.map(function (item) {
            // console.log(item)
              item.chkDisabled= true;
              item.nocheck =true;
						if (item.children && item.children.length > 0) {
							var childrenCheckOption = item.children;
							var newChildren = childrenCheckOption.map(function (itm) {
								// 判断选中项，true设置cheked=true，反之设为false
                var isCheckedOption = viewData.approver.userId === itm.userId;
								if (isCheckedOption) {
									itm.checked = true; // 为true时zTree勾选当前项
								} else {
									itm.checked = false;
								}
								return itm;
							});
							item.children = newChildren;
							return item;
						} else {
              return item;
            }
          });
          $.fn.zTree.init($("#treeRadioDemo"), radioSetting, viewCheckedRadioPerson); // 加载ztree-radio
          var zTreeRadioObj = $.fn.zTree.getZTreeObj("treeRadioDemo"); // ztree的Id
					zTreeRadioObj.expandAll(false); // 收起所有节点
          zTreeRadioOnCheck(); // 展示右侧选中项

          // 设置编辑默认选中值
          approvedBy = [];
          approvedBy.push(viewData.approver.userId);
				}
      }
    }
  });
}